﻿#define DEBUG_AGENT

using System;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Info;
using System.Linq;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml;
using System.Xml.Linq;


namespace UpdateTileAgent
{
    using WeiboSdk;
    using WeiboBulletin.Model;
    using System.Windows.Controls;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;

    public class ScheduledAgent : ScheduledTaskAgent
    {
        public static readonly string AgentName = "UpdateTileTask";
        public static readonly string AgentDescription = "UpdateTileTask";
        public static readonly string AgentTokenFile = "token";

        private Setting setting;

        static ScheduledAgent()
        {
            WeiboSdk.SdkData.AppKey =    "1702321919";
            WeiboSdk.SdkData.AppSecret = "33f358bc61bf0dcdd246c3b7365ac0f5";
            WeiboSdk.SdkData.AesKey =    "bfac82660ed24cfaacd1e32efabd98c3";
            WeiboSdk.SdkData.AesIV =     "a442fcbda9fa85d8";
        }

        private static volatile bool _classInitialized;
        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            if (Microsoft.Phone.Shell.ShellTile.ActiveTiles.First() != null)
            {
                try
                {
                    setting = Setting.GetCurrentAppSetting();
                    
                    if (setting.UpdateIntervalInMinutesInWifi > 0)
                    {
                        ShowWeiboToast();
                    }
                }
                catch
                {
                    NotifyComplete();
                }

                return;
            }

#if DEBUG_AGENT
            ScheduledActionService.LaunchForTest(ScheduledAgent.AgentName, TimeSpan.FromSeconds(30));
#endif

            NotifyComplete();
        }


        private void ShowWeiboToast()
        {
            var netEngine = new SdkNetEngine();

            // Define a new command base
            var cmdBase = new cmdFrendTimeLine
            {
                count = "20",
                acessToken = setting.AccessToken,
                acessTokenSecret = setting.AccessSecret,
            };

            // Request server, the last parameter is set as default (".xml")
            netEngine.RequestCmd(SdkRequestType.FRIENDS_TIMELINE, cmdBase, SendCallback);            
        }

        private void SendCallback(SdkRequestType requestType, SdkResponse response)
        {
            if (response.errCode == SdkErrCode.SUCCESS)
            {
                // Parse the response content
                XElement statusXml = XElement.Parse(response.content);

                var statusCollection = from XElement statusElement in statusXml.Descendants("status")
                                       select new StatusItem(statusElement , statusElement.Element("user"));

                var s = statusCollection.First();
                if (s.CreateTime == setting.LastPostCreateTime)
                {
                    var e = statusCollection.GetEnumerator();

                    while (e.MoveNext())
                    {
                        if (e.Current.CreateTime == setting.LastShowedPostCreateTime)
                        {
                            break;
                        }
                    }

                    if (e.MoveNext())
                    {
                        s = e.Current;
                    }
                    else
                    {
                        s = null;
                    }
                }
                else
                {
                    setting.LastPostCreateTime = s.CreateTime;
                    setting.LastShowedPostCreateTime = null;
                }

                if (s != null)
                {
                    setting.LastShowedPostCreateTime = s.CreateTime;
                    Setting.SetCurrentAppSetting(setting);

                    ShellToast toast = new ShellToast();
                    toast.Title = s.User.Name + ":";
                    toast.Content = s.Message;
                    toast.Show();
                    
                    // If debugging is enabled, launch the agent again in one minute.
#if DEBUG_AGENT
                    ScheduledActionService.LaunchForTest(ScheduledAgent.AgentName, 
                        TimeSpan.FromMinutes(setting.UpdateIntervalInMinutesInWifi));
#endif
                    //Deployment.Current.Dispatcher.BeginInvoke(() =>
                    //    {
                            StandardTileData tile = new StandardTileData();
                            tile.Title = s.User.Name;
                            tile.BackgroundImage = new Uri(s.User.ProfileImage, UriKind.Absolute);
                            tile.BackContent = s.Message;
                            tile.BackTitle = s.CreateTime;
                            if (s.ThumbnailPic != null)
                            {
                                tile.BackBackgroundImage = new Uri(s.ThumbnailPic);
                            }

                            Microsoft.Phone.Shell.ShellTile.ActiveTiles.First().Update(tile);

                            // Call NotifyComplete to let the system know the agent is done working.
                            NotifyComplete();
                    //    }
                    //);
                }                
            }
        }

        private string CreateTileImage(string sourceUrl)
        {
            Grid grid = new Grid()
            {
                Background = new ImageBrush()
                {
                    ImageSource = new BitmapImage
                    {
                        UriSource = new Uri(sourceUrl, UriKind.Absolute),
                        CreateOptions = BitmapCreateOptions.IgnoreImageCache,
                    },                    
                     
                },
                //(SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"],
                Width = 173,
                Height = 173
            };

            var imgs = new BitmapImage();
            imgs.ImageFailed+= delegate(object sender, ExceptionRoutedEventArgs e)
            {
                //
                imgs = null;
            };

            imgs.ImageOpened += delegate(object sender, RoutedEventArgs e)
            {
                //
                imgs = null;
            };

            imgs.UriSource = new Uri(sourceUrl, UriKind.Absolute);
            imgs.CreateOptions = BitmapCreateOptions.IgnoreImageCache;

            Image profileImage = new Image()
            {
                Height = 173,
                Width = 173,
                Source = imgs,
            };
            
            //profileImage.Arrange(new Rect(173 - 50, 0, 50, 50));
            //grid.Children.Add(profileImage);
            grid.Arrange(new Rect(0d, 0d, 173, 173));
            WriteableBitmap wbmp = new WriteableBitmap(grid, null);
            
            string tiledirectory = "Shared/ShellContent/tiles";
            string fullPath = tiledirectory + @"/" + "LiveTile.jpg";
            
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.DirectoryExists(tiledirectory))
                {
                    store.CreateDirectory(tiledirectory);
                }

                using (var stream = store.OpenFile(fullPath, System.IO.FileMode.OpenOrCreate))
                {
                    wbmp.SaveJpeg(stream, 173, 173, 0, 100);
                }
            }
            return "isostore:/" + fullPath;
        }
    }
}
